'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import {
  Row, Col, Image, Typography, Button, InputNumber, Card, 
  Descriptions, Tag, Space, Breadcrumb, message, Divider, Rate
} from 'antd'
import {
  ShoppingCartOutlined, HeartOutlined, ShareAltOutlined,
  StarFilled, SafetyOutlined, TruckOutlined
} from '@ant-design/icons'
import Link from 'next/link'
import { request } from '@/utils/request'
import { API_ENDPOINTS, IMAGE_CONFIG } from '@/utils/constants'

const { Title, Text, Paragraph } = Typography

interface Product {
  id: number
  name: string
  description: string
  price: number
  stockQuantity: number
  unit: string
  origin: string
  species: string
  processingMethod: string
  grade: string
  imageUrl: string
  images: string
  status: string
  categoryName: string
  weightPerUnit: number
  createdAt: string
}

interface TraceabilityInfo {
  batchNumber: string
  fishingVessel: string
  fishingLocation: string
  fishingDate: string
  processingFacility: string
  processingDate: string
  qrCodeUrl: string
}

export default function ProductDetailPage() {
  const params = useParams()
  const router = useRouter()
  const [product, setProduct] = useState<Product | null>(null)
  const [traceability, setTraceability] = useState<TraceabilityInfo[]>([])
  const [loading, setLoading] = useState(true)
  const [quantity, setQuantity] = useState(1)
  const [currentImageIndex, setCurrentImageIndex] = useState(0)

  const productId = params.id as string

  useEffect(() => {
    if (productId) {
      loadProductDetail()
      loadTraceabilityInfo()
    }
  }, [productId])

  const loadProductDetail = async () => {
    try {
      const response = await request.get(`${API_ENDPOINTS.PRODUCTS.DETAIL}/${productId}`)
      if (response.code === 200) {
        setProduct(response.data)
      } else {
        message.error('产品不存在')
        router.push('/products')
      }
    } catch (error: any) {
      message.error(error.message || '加载产品详情失败')
      router.push('/products')
    } finally {
      setLoading(false)
    }
  }

  const loadTraceabilityInfo = async () => {
    try {
      const response = await request.get(`${API_ENDPOINTS.TRACE.QUERY}/product/${productId}`)
      if (response.code === 200) {
        setTraceability(response.data)
      }
    } catch (error) {
      console.error('Failed to load traceability info:', error)
    }
  }

  const addToCart = async () => {
    try {
      const response = await request.post(`${API_ENDPOINTS.CART.ADD}?productId=${productId}&quantity=${quantity}`)
      if (response.code === 200) {
        message.success('添加到购物车成功')
      }
    } catch (error: any) {
      if (error.message.includes('401')) {
        message.error('请先登录')
        router.push('/login')
      } else {
        message.error(error.message || '添加失败')
      }
    }
  }

  const buyNow = async () => {
    try {
      await addToCart()
      router.push('/cart')
    } catch (error) {
      // 错误已在addToCart中处理
    }
  }

  if (loading || !product) {
    return (
      <div style={{ padding: '50px', textAlign: 'center' }}>
        <Text>加载中...</Text>
      </div>
    )
  }

  const images = product.images ? JSON.parse(product.images) : []
  const allImages = [product.imageUrl, ...images].filter(Boolean)

  return (
    <div style={{ padding: '20px', minHeight: '100vh', background: '#f5f5f5' }}>
      {/* 面包屑导航 */}
      <Breadcrumb style={{ marginBottom: '20px' }}>
        <Breadcrumb.Item><Link href="/">首页</Link></Breadcrumb.Item>
        <Breadcrumb.Item><Link href="/products">产品列表</Link></Breadcrumb.Item>
        <Breadcrumb.Item>{product.name}</Breadcrumb.Item>
      </Breadcrumb>

      <Card>
        <Row gutter={[32, 32]}>
          {/* 产品图片 */}
          <Col xs={24} md={12}>
            <div style={{ textAlign: 'center' }}>
              <Image
                width="100%"
                height={400}
                src={allImages[currentImageIndex] || IMAGE_CONFIG.DEFAULT_PRODUCT}
                alt={product.name}
                style={{ objectFit: 'cover', borderRadius: '8px' }}
              />
              
              {/* 缩略图 */}
              {allImages.length > 1 && (
                <div style={{ marginTop: '16px', display: 'flex', gap: '8px', justifyContent: 'center' }}>
                  {allImages.map((img, index) => (
                    <Image
                      key={index}
                      width={60}
                      height={60}
                      src={img}
                      alt={`${product.name} ${index + 1}`}
                      style={{ 
                        objectFit: 'cover', 
                        borderRadius: '4px',
                        border: currentImageIndex === index ? '2px solid #1890ff' : '1px solid #d9d9d9',
                        cursor: 'pointer'
                      }}
                      preview={false}
                      onClick={() => setCurrentImageIndex(index)}
                    />
                  ))}
                </div>
              )}
            </div>
          </Col>

          {/* 产品信息 */}
          <Col xs={24} md={12}>
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              {/* 产品标题 */}
              <div>
                <Title level={2} style={{ marginBottom: '8px' }}>{product.name}</Title>
                <Space>
                  {product.grade && (
                    <Tag color="gold" icon={<StarFilled />}>{product.grade}级</Tag>
                  )}
                  <Tag color={product.stockQuantity > 0 ? 'green' : 'red'}>
                    {product.stockQuantity > 0 ? '有库存' : '无库存'}
                  </Tag>
                  <Rate disabled defaultValue={4.5} style={{ fontSize: '14px' }} />
                  <Text type="secondary">(4.5分)</Text>
                </Space>
              </div>

              {/* 价格 */}
              <div>
                <Text style={{ fontSize: '28px', color: '#ff4d4f', fontWeight: 'bold' }}>
                  ￥{product.price.toFixed(2)}
                </Text>
                <Text style={{ fontSize: '16px', marginLeft: '8px' }}>/{product.unit}</Text>
              </div>

              {/* 产品描述 */}
              <div>
                <Paragraph style={{ fontSize: '16px', lineHeight: '1.6' }}>
                  {product.description}
                </Paragraph>
              </div>

              {/* 产品规格 */}
              <Descriptions column={1} size="small">
                <Descriptions.Item label="产地">{product.origin}</Descriptions.Item>
                <Descriptions.Item label="品种">{product.species}</Descriptions.Item>
                <Descriptions.Item label="加工方式">{product.processingMethod}</Descriptions.Item>
                <Descriptions.Item label="单体重量">
                  {product.weightPerUnit ? `${product.weightPerUnit}kg` : '未指定'}
                </Descriptions.Item>
                <Descriptions.Item label="库存数量">
                  {product.stockQuantity}{product.unit}
                </Descriptions.Item>
              </Descriptions>

              {/* 购买操作 */}
              <div style={{ background: '#f9f9f9', padding: '20px', borderRadius: '8px' }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <Text strong>数量：</Text>
                    <InputNumber
                      min={1}
                      max={product.stockQuantity}
                      value={quantity}
                      onChange={(value) => setQuantity(value || 1)}
                      disabled={product.stockQuantity === 0}
                    />
                    <Text type="secondary">{product.unit}(库存{product.stockQuantity}{product.unit})</Text>
                  </div>
                  
                  <Row gutter={[16, 16]}>
                    <Col span={12}>
                      <Button 
                        type="primary" 
                        size="large" 
                        block
                        icon={<ShoppingCartOutlined />}
                        onClick={addToCart}
                        disabled={product.stockQuantity === 0}
                      >
                        加入购物车
                      </Button>
                    </Col>
                    <Col span={12}>
                      <Button 
                        type="primary" 
                        size="large" 
                        block
                        danger
                        onClick={buyNow}
                        disabled={product.stockQuantity === 0}
                      >
                        立即购买
                      </Button>
                    </Col>
                  </Row>
                  
                  <Row gutter={[16, 16]}>
                    <Col span={12}>
                      <Button size="large" block icon={<HeartOutlined />}>
                        收藏
                      </Button>
                    </Col>
                    <Col span={12}>
                      <Button size="large" block icon={<ShareAltOutlined />}>
                        分享
                      </Button>
                    </Col>
                  </Row>
                </Space>
              </div>

              {/* 服务保障 */}
              <div>
                <Space direction="vertical">
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <SafetyOutlined style={{ color: '#52c41a', marginRight: '8px' }} />
                    <Text>品质保证：源头直供，品质保证</Text>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <TruckOutlined style={{ color: '#1890ff', marginRight: '8px' }} />
                    <Text>冷链配送：全程低温运输，保证新鲜</Text>
                  </div>
                </Space>
              </div>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 溯源信息 */}
      {traceability.length > 0 && (
        <Card title="产品溯源" style={{ marginTop: '20px' }}>
          <Row gutter={[16, 16]}>
            {traceability.map((trace, index) => (
              <Col xs={24} md={12} lg={8} key={index}>
                <Card size="small">
                  <Descriptions column={1} size="small">
                    <Descriptions.Item label="批次号">{trace.batchNumber}</Descriptions.Item>
                    <Descriptions.Item label="渔船">{trace.fishingVessel}</Descriptions.Item>
                    <Descriptions.Item label="捕捞地点">{trace.fishingLocation}</Descriptions.Item>
                    <Descriptions.Item label="捕捞日期">{trace.fishingDate}</Descriptions.Item>
                    <Descriptions.Item label="加工厂">{trace.processingFacility}</Descriptions.Item>
                    <Descriptions.Item label="加工日期">{trace.processingDate}</Descriptions.Item>
                  </Descriptions>
                  {trace.qrCodeUrl && (
                    <div style={{ textAlign: 'center', marginTop: '10px' }}>
                      <Image width={100} src={trace.qrCodeUrl} alt="溯源二维码" />
                    </div>
                  )}
                </Card>
              </Col>
            ))}
          </Row>
        </Card>
      )}
    </div>
  )
}